#include "include/qeasycurl.h"

QEasyCurl::QEasyCurl()
{
    /* Initailize the easy curl handle. */
    m_pCurl = curl_easy_init();
}

/* Release the resource of the curl and slist. */
QEasyCurl::~QEasyCurl()
{
    curl_easy_cleanup(m_pCurl);
    //curl_slist_free_all(&m_slist);
}

/* Set the data pointer which will used in the call back function. */
void QEasyCurl::setWriteData(void **data)
{
    m_pWrite_data = data;
    curl_easy_setopt(m_pCurl, CURLOPT_WRITEDATA, (void*)m_pWrite_data);
}

void QEasyCurl::setDebugData(void **data)
{
    m_pDebug_data = data;
    curl_easy_setopt(m_pCurl, CURLOPT_DEBUGDATA, (void*)m_pDebug_data);
}

/* Set the call back function of the result pre-process. */
void QEasyCurl::setWriteCallBackFunc(curl_wirtecbkfunc_t func)
{
    if (func) {
        m_write_callback_func = func;
        curl_easy_setopt(m_pCurl, CURLOPT_WRITEFUNCTION, m_write_callback_func);
    }
}

void QEasyCurl::setDebugCallBackFunc(curl_debugcbkfunc_t func)
{
    if (func) {
        m_debug_callback_func = func;
        curl_easy_setopt(m_pCurl, CURLOPT_DEBUGFUNCTION, m_debug_callback_func);
        curl_easy_setopt(m_pCurl, CURLOPT_VERBOSE, 1L);
        curl_easy_setopt(m_pCurl, CURLOPT_FOLLOWLOCATION, 1L);
    }
}

/*
*   Set the current user para only one,
*   and we need to choose the setting according to the method.
*/
void QEasyCurl::setParameter(void *para)
{
    if (para) {
        m_user_para = QString((char*)para);
        m_pUser_para = para; //  don't use.
        
        if (m_method=="POST") {
            curl_easy_setopt(m_pCurl, CURLOPT_POSTFIELDS, m_user_para.toStdString().c_str());
        } else {
            /* 
            *   Add the parameter behind the url and reset it.
            *   Here, I don't perfect it. 
            */
            m_url.append(m_user_para);
            curl_easy_setopt(m_pCurl, CURLOPT_URL, m_url.toStdString().c_str());
        }
    }
}

/* Set the method of the http request. */
void QEasyCurl::setMethod(const QString &method)
{
    m_method = method;
    curl_easy_setopt(m_pCurl, CURLOPT_CUSTOMREQUEST, m_method.toStdString().c_str());
}

/*
*   After calling this function successfully,
*   we can get the data from the writedata.
*/
int QEasyCurl::sendRequest()
{
    int ret = curl_easy_perform(m_pCurl);
    if (ret == CURLE_OK)
        ;//emit sendWriteData(p_write_data);
}

/* Set the url of the curl instance. */
void QEasyCurl::setUrl(const QString &url)
{
    m_url = url;
    curl_easy_setopt(m_pCurl, CURLOPT_URL, m_url.toStdString().c_str());
}

/*  */
void QEasyCurl::addsList(const QString &slist)
{
    curl_slist_append(&m_slist, slist.toStdString().c_str());
}
